package org.jeecg.extra.exception;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.extra.enums.ValidEnum;
import org.jeecg.extra.utils.I18nMessage;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 参数异常处理器
 * 
 * @Author scott
 * @Date 2019
 */
@RestControllerAdvice
@Slf4j
public class JeecgBootExtraExceptionHandler {
	private static final String EXCEPTION_MESSAGE = "i18n/valid_message";

	/**
	 * 参数校验异常
	 *
	 * @param e 异常对象
	 * @return 异常描述对象
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		log.error(I18nMessage.bundle(EXCEPTION_MESSAGE).getMessage("title"), e);

		BindingResult bindingResult = e.getBindingResult();
		ValidEnum errorCode = ValidEnum.TEMP;
		if (bindingResult.hasErrors()) {
			FieldError fieldError = bindingResult.getFieldError();
			if (fieldError != null) {
				ValidEnum validEnum = ValidEnum.getInstanceByFieldError(fieldError);
				if (ObjectUtil.isNotNull(validEnum)) {
					// 存在ValidatedEnum枚举对象中，使用对应提示
					errorCode.setMessage(validEnum.getMessage());
				} else {
					// 不存在, 则使用默认提示或者使用手动编写message提示
					errorCode.setMessage(fieldError.getDefaultMessage());
				}
			}
		}

		return Result.error(500, errorCode.getMessage());
	}
}
